<!-- 食谱查看 -->
<template>
	<div class="">
		<cus-search class="mb_20">
			<cus-search-item>
				<Form class="flex" ref="formValidate" :model="form" :label-width="120">
					<FormItem class="mr_48 mb_20" label="食谱周期:">
						<div class="flex">
							<el-date-picker type="week" format="yyyy 第 WW 周" :picker-options="{ firstDayOfWeek: 1 }"
								v-model="pickerTime" placeholder="选择周" @change="dateWeekChange" transfer :clearable="false">
							</el-date-picker>
						</div>
					</FormItem>
					<!-- <FormItem class="mr_48" label="审核状态:" prop="organAuditState">
            <Select v-model="form.organAuditState" placeholder="全部" clearable style="width: 200px">
              <Option value="all">全部</Option>
              <Option :value="1">待审核</Option>
              <Option :value="2">已审核通过</Option>
              <Option :value="3">已驳回</Option>
            </Select>
          </FormItem> -->
					<FormItem class="mr_48 mb_20" label="伙食单位:" prop="unitCode">
						<Select v-model="form.unitCode" placeholder="全部" clearable style="width: 200px">
							<Option :value="item.unitCode" v-for="(item, index) in subCanteenList" :key="index">{{
								item.unitName }}</Option>
						</Select>
					</FormItem>
					<Button class="mr_24 mb_20" type="primary" @click="
						pages.page = 1
					onInit()
						">查询</Button>
					<Button class="mr_24 mb_20" type="default" @click="reset()">重置</Button>
				</Form>
			</cus-search-item>
		</cus-search>
		<div class="content-bottom">
			<cus-card>
				<div class="btnBox fw">
					<div class="fz" v-if="!loading">
						本周已提报审核单位 {{ submitNum || 0 }} 个 未提报单位<a @click="onNotSubmitModel()">
							{{ notSubmitNum || 0 }}
						</a>
						个
					</div>
				</div>
				<cusTable border ref="selection" :loading="loading" :span-method="handleSpan" :columns="columns"
					:data="RecipeData" :bottomClass="['cus_page']">
					<template slot-scope="{ row }" slot="operation">
						<div class="flex">
							<Button class="mr_10" type="primary" size="small"
								:style="{ color: '#ffffff', padding: '0 8px' }" @click="onShow(row.mealPlanId)">
								详情
							</Button>
							<!-- 三期工期 -->
							<Button type="primary" size="small"   v-if="[2,1].indexOf(row.organAuditState) != -1" :style="{ color: '#ffffff', padding: '0 8px' }"
								@click="onAudit(row)">
								{{ row.organAuditState == 2 ? '撤销审核' : '审核' }}
							</Button>
						</div>
					</template>
				</cusTable>
				<div class="cus_page">
					<cus-page :data="pages" class="mt_20" @pageChange="getRecipeListApi()"></cus-page>
				</div>
			</cus-card>
		</div>
		<recipeDetails ref="recipeDetails"></recipeDetails>
		<recipeModal ref="recipeModal" @refetch="refetch"></recipeModal>
		<notSubmitModel ref="notSubmitModel"></notSubmitModel>
	</div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import { RecipeList } from '@/api/organ/dishesModule'
import { getSubCanteenList } from '@/api/organ/organization'
// 食谱详情页面
import recipeDetails from './components/recipeDetails.vue'
// 食谱审核
import recipeModal from './components/recipeModal.vue'
// 未提交审核页面
import notSubmitModel from './components/notSubmitModel.vue'
export default {
	//import引入的组件需要注入到对象中才能使用
	components: { recipeDetails, recipeModal, notSubmitModel },
	data() {
		//这里存放数据
		return {
			form: {
				dateTime: [
					new Date(
						new Date().setHours(0, 0, 0) -
						(new Date().getDay() - 8) * 24 * 60 * 60 * 1000
					),
					new Date(
						new Date().setHours(0, 0, 0) +
						(14 - new Date().getDay()) * 24 * 60 * 60 * 1000
					)
				], // 食谱时间
				organAuditState: 'all', // 机关审核状态1-待审核、2-已审核通过、3-已驳回、4-无需审核
				unitCode: 'all' // 提交单位编码
			},
			notSubmitNum: null, // 未提交数量
			submitNum: null, // 已提交数量
			pickerTime:
				new Date().setHours(0, 0, 0) -
				(new Date().getDay() - 8) * 24 * 60 * 60 * 1000,
			tableHeight: 0,
			loading: false,
			subCanteenList: [{ unitCode: 'all', unitName: '全部' }], //下级单位列表
			RecipeData: [], // 食谱列表
			columns: [
				{
					title: '序号',
					width: 70,
					key: 'index',
					align: 'center'
				},
				{
					title: '伙食单位',
					key: 'unitName',
					minWidth: 120,
					resizable: true,
					align: 'center'
				},
				{
					title: '食谱周期',
					key: 'planDate',
					minWidth: 120,
					resizable: true,
					align: 'center'
				},
				{
					title: '档口',
					key: 'stallName',
					minWidth: 150,
					// width: 190,
					//   sortable: true,
					resizable: true,
					align: 'center'
				},
				{
					title: '提交时间',
					key: 'submitTime',
					minWidth: 120,
					// sortable: true,
					resizable: true,
					align: 'center'
				},
				{
					title: '审核状态',
					key: 'organAuditStateName',
					minWidth: 120,
					resizable: true,
					align: 'center'
				},
				{
					title: '备注',
					key: 'remark',
					minWidth: 200,
					resizable: true,
					align: 'center'
				},
				{
					title: '操作',
					minWidth: 180,
					// fixed: "right",
					slot: 'operation',
					align: 'center'
				}
			],
			pages: {
				page: 1,
				pageSize: 10,
				pageTotal: 0
			}
		}
	},
	//监听属性 类似于data概念
	computed: {},
	//监控data中的数据变化
	watch: {},
	mounted() {
		console.log(this.$route.query)
		if (this.$route.query.id) this.onShow(this.$route.query.id)
		this.getSubCanteenListApi()
		this.onInit()
	},
	//方法集合
	methods: {
		refetch() {
			this.getRecipeListApi()
		},
		// 初始化
		onInit() {
			this.getRecipeListApi()
			setTimeout(() => {
				this.tableHeight = window.innerHeight - 373 // 表格自适应高度
			}, 100)
			window.addEventListener('resize', this.tableHeightChange, true)
		},
		// 表格高度变化
		tableHeightChange() {
			this.tableHeight = 0
			setTimeout(() => {
				this.tableHeight = window.innerHeight - 373 // 表格自适应高度
			}, 100)
		},
		// 重置搜索
		reset() {
			this.$refs['formValidate'].resetFields();
			(this.form.dateTime = [
				new Date(
					new Date().setHours(0, 0, 0) -
					(new Date().getDay() - 8) * 24 * 60 * 60 * 1000
				),
				new Date(
					new Date().setHours(0, 0, 0) +
					(14 - new Date().getDay()) * 24 * 60 * 60 * 1000
				)
			]);
			(this.pickerTime = new Date().setHours(0, 0, 0) - (new Date().getDay() - 8) * 24 * 60 * 60 * 1000);
			this.pages.page = 1
			this.onInit()
		},
		// 表格行修改
		handleSpan({ row, column, rowIndex, columnIndex }) {
			if (columnIndex < 3) {
				//计算合并的行数列数
				let x = row.mergeColumn == 0 ? 0 : row.mergeColumn
				let y = row.mergeColumn == 0 ? 0 : 1
				return [x, y]
			}
		},
		// 未提交审核展示
		onNotSubmitModel() {
			this.$refs['notSubmitModel'].show(this.form)
		},
		// 食谱详情展示
		onShow(row) {
			if (row) {
				this.$refs['recipeDetails'].id = row
				this.$refs['recipeDetails'].show()
			}
		},
		// 处理数据添加合并行
		assembleData(data) {
			let names = []
			//筛选出不重复的 name值,将其放到 names数组中
			data.forEach((e) => {
				if (!names.includes(e.unitName)) {
					names.push(e.unitName)
				}
			})
			let nameNums = []
			//将names数组中的 name值设置默认合并0个单元格,放到 nameNums中
			names.forEach((e) => {
				nameNums.push({ name: e, num: 0, index: 1 })
			})
			//计算每种 name值所在行需要合并的单元格数
			data.forEach((e) => {
				nameNums.forEach((n) => {
					if (e.unitName == n.name) {
						n.num++
					}
				})
			})
			// 重新设置序号
			let index = 1
			//将计算后的合并单元格数整合到 data中
			data.forEach((e) => {
				nameNums.forEach((n) => {
					if (e.unitName == n.name) {
						if (names.includes(e.unitName)) {
							e.mergeColumn = n.num
							e.index = index
							index++
							//删除已经设置过的值(防止被合并的单元格进到这个 if 语句中)
							names.splice(names.indexOf(n.name), 1)
						} else {
							//被合并的单元格设置为 0
							e.mergeColumn = 0
						}
					}
				})
			})
			//将整理后的数据交给表格渲染
			this.RecipeData = data
		},
		// 审核模块展示
		onAudit(row) {
			let params = new Object()
			params.mealPlanId = row.mealPlanId
			params.organAuditState = row.organAuditState
			this.$refs['recipeModal'].show(params)
		},
		// 时间 改变后处理时间格式
		dateWeekChange(time) {
			this.planIds = []
			this.form.dateTime[0] = this.getCurrentWeek(time)[0]
			this.form.dateTime[1] = this.getCurrentWeek(time)[6]
		},
		// 获取本周日期组件处理
		getWeek() {
			this.form.dateTime[0] = moment().weekday(0).format('YYYY-MM-DD') //本周一
			this.form.dateTime[1] = moment().weekday(6).format('YYYY-MM-DD') //本周日
		},
		// 获取本周日期组件处理
		getCurrentWeek(date) {
			let nowData = new Date(date) //传入时间参数,如 2021-11-09 获取给定日期所属的周 日期
			let currentDay = nowData.getDay()
			if (currentDay == 0) {
				currentDay = 7
			}
			let beforweek = [],
				afterWeek = []
			for (let i = 1; i <= 7; i++) {
				if (currentDay - i >= 0) {
					let DayTime =
						nowData.getTime() - (currentDay - i) * 24 * 60 * 60 * 1000
					beforweek.push(new Date(DayTime).Format('yyyy-MM-dd'))
				} else {
					let DayTime = nowData.getTime() + (8 - i) * 24 * 60 * 60 * 1000
					afterWeek.push(new Date(DayTime).Format('yyyy-MM-dd'))
				}
			}
			afterWeek = afterWeek.reverse()
			let dateList = [...beforweek, ...afterWeek]
			return dateList
		},
		// 获取所有的伙食单位-----------------------接口
		getSubCanteenListApi() {
			this.loading = true
			return new Promise((resolve) => {
				getSubCanteenList({
					currentPage: 1,
					pageSize: 1000
				}).then((res) => {
					this.loading = false
					if (res.code === 1) {
						this.subCanteenList = this.subCanteenList.concat(res.data.list)
						resolve()
					}
				})
			})
		},
		// 获取食谱列表
		getRecipeListApi() {
			this.loading = true;
			return new Promise((resolve) => {
				let params = {
					startDate: this.form.dateTime[0]
						? new Date(this.form.dateTime[0]).Format('yyyy-MM-dd')
						: null,
					stopDate: this.form.dateTime[1]
						? new Date(this.form.dateTime[1]).Format('yyyy-MM-dd')
						: null,
					organAuditState:
						this.form.organAuditState == 'all' ? '' : this.form.organAuditState,
					unitCode: this.form.unitCode == 'all' ? '' : this.form.unitCode,
					currentPage: this.pages.page,
					pageSize: this.pages.pageSize
				}
				RecipeList(params).then((res) => {
					this.loading = false
					if (res.code == 1) {
						this.RecipeData = []
						this.notSubmitNum = res.data.notSubmitNum
						this.submitNum = res.data.submitNum
						res.data.mealPlanUnitPagePageVo.list.forEach((item) => {
							if (item.mealPlanUnitStalls) {
								item.mealPlanUnitStalls.forEach((it) => {
									it.unitName = item.unitName
									it.planDate = item.planDate
								})
								this.RecipeData.push(...item.mealPlanUnitStalls)
							}
						})
						//  this.RecipeData = res.data.mealPlanUnitPagePageVo.list
						this.assembleData(this.RecipeData)
						this.pages.pageTotal = res.data.mealPlanUnitPagePageVo.total
					}
				})
			})
		}
	}
}
</script>

<style scoped lang="less">
[v-cloak] {
	display: none;
}

.fw {
	display: flex;
	justify-content: space-between;
}

.fz {
	font-size: 20px;
	font-family: PingFang SC-Medium, PingFang SC;
	font-weight: 500;
	color: #333333;
	line-height: 23px;
}
</style>
